<template>
  <div class="createPost-container">
    <el-steps v-if="this.productType == 5 || this.productType == 6 || this.productType == 7 || this.productType == 9 || productType == 10" style="margin-top: 10px;" :active="activeStep" align-center>
      <el-step title="编辑商品"></el-step>
      <el-step title="编辑分润供应商"></el-step>
    </el-steps>
    <el-form v-if="activeStep == 1" v-loading="loading" ref="postForm" :model="postForm" :rules="rules" class="form-container">
      <div class="createPost-main-container">
        <el-row>
          <el-col :span="24">
            <div class="postInfo-container">
              <div style="width:100; display: flex; justify-content: center;">
                <div style="font-size:18px; color: black; weight: 400;">{{ title }}</div>
              </div>
              <el-form-item label="商品分类:" prop="categoryId" class="postInfo-container-item">
                <Cascader v-model="categoryId" :ids="categoryIds" ref="categoryId" placeholder="商品分类"
                  :options="categoryData" :props="props" class="filter-item" />
              </el-form-item>
            </div>
            
            <div class="postInfo-container">
              <el-form-item v-for="(item, index) in attributeList" :prop="item.fieldName" :key="index" class="postInfo-container-item">
                <span v-if='item.required === 1' style="color: red;">*</span>
                <el-input style="width: 200px" v-if="item.type === 1 && item.fieldName !== 'productionPlace' && item.fieldName !== 'warehouse'" v-model="postForm[item.fieldName]" :placeholder="item.attributeText" @input="(val)=>{handleInput(val,item)}" clearable/>
                <el-select style="width: 200px" v-if="item.type === 2"  v-model="postForm[item.fieldName]" :placeholder="item.attributeText" @change="(val)=>{handleInput(val,item)}" clearable>
                  <el-option
                    v-for="children in item.dinnerAttributeDetailList"
                    :key="children.id"
                    :label="children.name"
                    :value="children.id.toString()">
                  </el-option>
                </el-select>
                <el-date-picker style="width: 200px" v-if="item.type === 3"
                  v-model="postForm[item.fieldName]"
                  type="date"
                  :placeholder="'选择' + item.attributeText + '年份'" @change="(val)=>{handleInput(val,item)}" format="yyyy年MM月dd日" value-format="yyyy-MM-dd HH:mm:ss" clearable>
                </el-date-picker>
              </el-form-item>
            </div>
            <div class="postInfo-container">
              <!-- 仓储地 -->
              <el-form-item class="postInfo-container-item">
                <AddressCascader style="width: 200px" v-if="requiredWarehouse" v-model="warehouseOptions" @selectAddressDetail="(val)=>{handleAddress(val,'warehouse')}" placeholder="选择仓储地"/>
              </el-form-item>

              <!-- 产地 -->
              <el-form-item class="postInfo-container-item">
                <AddressCascader style="width: 200px" v-if="requiredProductionPlace" v-model="productionPlaceOptions" @selectAddressDetail="(val)=>{handleAddress(val,'productionPlace')}" placeholder="选择产地" />
              </el-form-item>
              <el-form-item class="postInfo-container-item">
                <el-input style="width: 400px" v-if="requiredProductionPlace" v-model="postForm.productionAddress" placeholder="产地详细地址" />
              </el-form-item>
            </div>

            <div v-if="productType == '5' || productType == '6' || productType == '7'|| productType == '8' || productType == '9' || productType == '10'" class="postInfo-container">
              <el-form-item label="众茶优选:" prop="zcyxCategoryId" class="postInfo-container-item">
                <Cascader v-model="zcyxCategoryId" :ids="zcyxCategoryIds" ref="zcyxCategoryId" placeholder="商品分类"
                  :options="zcyxCategoryData" :props="props" class="filter-item" />
              </el-form-item>
            </div>
            <div v-if="productType == '5'" class="postInfo-container">
              <el-form-item label="新品上架:" prop="isNewProduct" class="postInfo-container-item">
                <el-select style="width: 200px" v-model="postForm.isNewProduct" placeholder="新品上架" clearable>
                  <el-option
                    v-for="children in commonOption" :key="children.value" :label="children.label" :value="children.value">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="尾货商品:" prop="isTailCargo" class="postInfo-container-item">
                <el-select style="width: 200px" v-model="postForm.isTailCargo" placeholder="尾货商品" clearable>
                  <el-option
                    v-for="children in commonOption" :key="children.value" :label="children.label" :value="children.value">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="爆款商品:" prop="isHotProduct" class="postInfo-container-item">
                <el-select style="width: 200px" v-model="postForm.isHotProduct" placeholder="爆款商品" clearable>
                  <el-option
                    v-for="children in commonOption" :key="children.value" :label="children.label" :value="children.value">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="虚拟销量:" prop="isHotProduct" class="postInfo-container-item">
                <el-input style="width: 200px" v-model="postForm.virtualSaleNum" type="number" oninput="value = value.replace(/^(0+)|[^\d]+/g,'');" placeholder="请输入" clearable/>
              </el-form-item>
            </div>

            <!-- 众茶优选经销商品才会出现 -->
            <div v-if="productType == '9'" class="postInfo-container">
              <el-form-item label="经销商品牌" prop="proxyBrandId" class="postInfo-container-item">
                <el-select style="width: 200px" v-model="postForm.proxyBrandId" placeholder="经销商品牌" clearable>
                  <el-option
                    v-for="children in brandOption" :key="children.value" :label="children.label" :value="children.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </div>

            <!-- <div v-if="this.productType == 5 || this.productType == 6 || this.productType == 7 || this.productType == 9 || this.productType == 10" class="postInfo-container">
              <el-form-item label="产品分润类型:" prop="splitType" class="postInfo-container-item">
                <el-select style="width: 200px" v-model="postForm.splitType" placeholder="新品上架" clearable>
                  <el-option
                    v-for="children in splitTypeOption" :key="children.value" :label="children.label" :value="children.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </div> -->

            <el-form-item style="margin-bottom: 40px;" prop="name">
              <MDinput v-model="postForm.name" :maxlength="100" name="name" required readonly>
                商品名称
              </MDinput>
            </el-form-item>
            <!-- <div class="postInfo-container">
              <el-form-item label="编号:" class="postInfo-container-item">
                <el-input v-model="postForm.identifier" placeholder="编号" />
              </el-form-item>
            </div> -->
            <el-form-item label="商品主图(仅限1张):" prop="image" style="margin-bottom: 30px;">
              <UploadImage :image.sync="postForm.image" :limit="1" :type=1 />
              
            </el-form-item>
            <el-form-item v-if="paramIsActivityGood == '1'" label="商品视频(仅限1个):" style="margin-bottom: 30px;">
              <Upload :defaultVideo.sync="postForm.productVideo" :mode="7"/>
            </el-form-item>
            <el-form-item label="商品轮播图(仅限6张):" style="margin-bottom: 30px;">
              <UploadImage :imageList.sync="images" :type=1 />
              <!-- <UpImgs :default-image.sync="images" :validWidth="750" :validHeight="750" :size="1"/>
							<span style="color:#ff8704;">图片限制750*750px，大小在1M内</span> -->
            </el-form-item>
            <div class="postInfo-container">
              <el-form-item label="排序值（越小越靠前）:" class="postInfo-container-item">
                <el-input v-model="postForm.sequence" type="number" placeholder="序号" />
              </el-form-item>
              <el-form-item v-if="productType == 0 || productType == 4 || productType == 5" label="是否是样品:" class="postInfo-container-item">
                <el-radio v-model="postForm.isSample" :label=false>否</el-radio>
                <el-radio v-model="postForm.isSample" :label=true>是</el-radio>
              </el-form-item>
              <el-form-item v-if="productType == 8" label="是否是免费样品:" class="postInfo-container-item">
                <el-radio v-model="postForm.isSample" :label=false>否</el-radio>
                <el-radio v-model="postForm.isSample" :label=true>是</el-radio>
              </el-form-item>
              <el-form-item v-if="productType == 8 && showStock" label="是否是股票:" class="postInfo-container-item">
                <el-radio v-model="postForm.isStock " :label=false>否</el-radio>
                <el-radio v-model="postForm.isStock" :label=true>是</el-radio>
              </el-form-item>
              <el-form-item v-if="productType == 9" label="是否是升级产品:" class="postInfo-container-item">
                <el-radio v-model="postForm.isFinanceProduct" :label=false>否</el-radio>
                <el-radio v-model="postForm.isFinanceProduct" :label=true>是</el-radio>
              </el-form-item>
              <!-- <el-form-item label="状态:" class="postInfo-container-item">
                <el-radio-group v-model="postForm.status">
                  <el-radio v-for="item in statusJson" :key="item.value" :label="item.value">
                    {{ item.label }}
                  </el-radio>
                </el-radio-group>
              </el-form-item> -->
            </div>
            <!-- <div class="postInfo-container">
              <el-form-item label="商城展示价格（元）:" prop="price" class="postInfo-container-item">
                <el-input v-model="postForm.price" type="number" placeholder="定价"/>
              </el-form-item>
            </div> -->
            <div class="postInfo-container">
              <el-form-item label="发货地:" prop="city" class="postInfo-container-item">
                <AddressCascader v-model="selectedOptions" @selectAddressDetail="selectAddressDetail" />
              </el-form-item>
              <!-- <el-form-item label="销量:" class="postInfo-container-item">
                <el-input v-model="postForm.saleNum" type="number" placeholder="销量" />
              </el-form-item> -->
              <!-- <el-form-item label="起订量:" class="postInfo-container-item">
                <el-input v-model="postForm.starNum" type="number" placeholder="起订量" />
              </el-form-item> -->
              <el-form-item label="计量单位:" prop="unit" class="postInfo-container-item">
                <el-input v-model="postForm.unit" placeholder="计量单位" />
              </el-form-item>
            </div>
            <div class="postInfo-container">
              <el-form-item label="仓位(商品没有入库指定数字仓，请选择合作仓):" prop="storeId" class="postInfo-container-item">
                <Cascader v-model="storeId" :ids="storeIds" ref="storeId" placeholder="仓位" :options="storeData"
                  :props="props" class="filter-item" />
              </el-form-item>
            </div>
          </el-col>
        </el-row>
        <el-card class="box-card" shadow="hover">
          <div slot="header" class="clearfix" style="position: relative;">
            <span>商品规格</span>
            <span class="sku_tip">(商品规格是最小的销售单位，每款商品可以设置多个规格，每个规格可以设置不同的价格、起订量)</span>
            <el-button style="float: right; padding: 3px 0" type="text" @click="addSkuItem()">添加商品规格</el-button>
          </div>
          <el-table :data="skuList" style="width: 100%">
            <!-- <el-table-column label="SKU编码">
              <template slot-scope="{row}">
                <el-input v-model="row.identifier" placeholder="请输入"></el-input>
              </template>
            </el-table-column> -->
            <el-table-column label="规格名称(例:冰岛357g/饼)">
              <template slot-scope="{row}">
                <div class="flexItem">
                  <span class="fuhao">*</span>
                  <el-input v-model="row.name" placeholder="请输入"></el-input>
                </div>
              </template>
            </el-table-column>
            <el-table-column v-if="productType == 0 || productType == 3 || productType == 5 || productType == 6 || productType == 7 || productType == 9 || productType == 10"
             :label="guestPriceLabel">
              <template slot-scope="{row}">
                <div class="flexItem">
                  <el-input v-model="row.guestPrice" @input="(val) => { handlePriceInput(val, row, 'guestPrice') }" placeholder="请输入"/>
                </div>
              </template>
            </el-table-column>
            <el-table-column v-if="productType == 5 || productType == 6 || productType == 7 || productType == 9 || productType == 10" label="供应商底价">
              <template slot-scope="{row}">
                <div class="flexItem">
                  <el-input v-model="row.costPrice" @input="(val) => { handlePriceInput(val, row, 'costPrice') }" placeholder="请输入"/>
                </div>
              </template>
            </el-table-column>
            <el-table-column :label="priceLabel">
              <template slot-scope="{row}">
                <div class="flexItem">
                  <span class="fuhao">*</span>
                  <el-input v-model="row.price" @input="(val) => { handlePriceInput(val, row, 'price') }" placeholder="请输入"/>
                </div>
              </template>
            </el-table-column>
            <!-- <el-table-column v-if="productType == 5 || productType == 9" :label="highPriceLabel">
              <template slot-scope="{row}">
                <div class="flexItem">
                  <el-input v-model="row.seniorMemberPrice" @input="(val) => { handlePriceInput(val, row, 'seniorMemberPrice') }" placeholder="请输入"/>
                </div>
              </template>
            </el-table-column> -->
            <el-table-column v-if="productType == 8" label="积分">
              <template slot-scope="{row}">
                <div class="flexItem">
                  <el-input v-model="row.score" type="number" oninput="value = value.replace(/^(0+)|[^\d]+/g,'');" placeholder="请输入"/>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="计量单位(例:饼/件/盒/斤等)">
              <template slot-scope="{row}">
                <div class="flexItem">
                  <span class="fuhao">*</span>
                  <el-input v-model="row.unit" placeholder="请输入" />
                </div>
              </template>
            </el-table-column>
            <el-table-column label="净含量(g)">
              <template slot-scope="{row}">
                <div class="flexItem">
                  <span class="fuhao">*</span>
                  <el-input v-model="row.weight" type="number" oninput="value = value.replace(/^(0+)|[^\d]+/g,'');" placeholder="请输入" />
                </div>
              </template>
            </el-table-column>
            <el-table-column label="库存数">
              <template slot-scope="{row}">
                <div class="flexItem">
                  <span class="fuhao">*</span>
                  <el-input v-model="row.store" type="number" oninput="value = value.replace(/^(0+)|[^\d]+/g,'');if(value.length>9) {value=value.slice(0,9)}" placeholder="请输入"></el-input>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="起订量">
              <template slot-scope="{row}">
                <div class="flexItem">
                  <span class="fuhao">*</span>
                  <el-input v-model="row.startNum" type="number" oninput="value = value.replace(/^(0+)|[^\d]+/g,'');" placeholder="请输入"></el-input>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="80">
              <template slot-scope="{$index}">
                <el-button type="text" size="small" class="user-btn-default" @click="deleteSkuItem($index)">删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
        <el-form-item v-if="productType == 1 || productType == 6 || productType == 7" label="秒杀时间:" prop="startDate" style="width:400px">
          <DatePicker :startDate.sync="postForm.seckillBeginTime" :endDate.sync="postForm.seckillEndTime" clearable />
        </el-form-item>
        
        <el-form-item prop="remark" style="margin-bottom: 30px;">
          <!-- 宽度设置成984，是为了跟详情页图片宽度一致，详情页宽度968，富文本自带margin 8 -->
          <Tinymce ref="editor" v-model="postForm.remark" :width="984" :height="400" />
        </el-form-item>
        <el-form-item style="margin-bottom: 30px;">
          <!-- 秒杀，经销，活动专区商品的新建与编辑 -->
          <el-button v-if="productType == 1 || productType == 2 || productType == 3"  type="success" @click="submitForm(2)">
            发布到众茶通小程序
          </el-button>
          <!-- 微商城商品的新建与编辑 -->
          <el-button v-else-if="productType == 4"  type="success" @click="submitForm(3)">
            发布到微商城
          </el-button>
          <!-- 众茶优选普通商品的新建与编辑 -->
          <el-button v-else-if="productType == 5"  type="success" @click="submitForm(4)">
            发布到小程序
          </el-button>
          <!-- 众茶优选秒杀商品的新建与编辑 -->
          <el-button v-else-if="productType == 6"  type="success" @click="submitForm(4)">
            发布到小程序
          </el-button>
          <!-- 众茶优选推广秒杀商品的新建与编辑 -->
          <el-button v-else-if="productType == 7"  type="success" @click="submitForm(4)">
            发布到小程序
          </el-button>
          <!-- 众茶优选积分商品的新建与编辑 -->
          <el-button v-else-if="productType == 8"  type="success" @click="submitForm(14)">
            发布到小程序
          </el-button>
          <!-- 众茶优选经销商品的新建与编辑 -->
          <el-button v-else-if="productType == 9"  type="success" @click="submitForm(4)">
            发布到小程序
          </el-button>
          <!-- 众茶优选专柜商品的新建与编辑 -->
          <el-button v-else-if="productType == 10"  type="success" @click="submitForm(4)">
            发布到小程序
          </el-button>
          <!-- 众茶优品商品的新建与编辑 -->
          <el-button v-else-if="productType == 11"  type="success" @click="submitForm(5)">
            发布到小程序
          </el-button>
          <!-- 服务商专区商品的新建与编辑 -->
          <el-button v-else-if="productType == 12"  type="success" @click="submitForm(2)">
            发布到小程序
          </el-button>
          <div v-else>
            <!-- 普通商品的新建与编辑 -->
            <el-button v-if="(postForm.type === 0 || postForm.type === 1)" type="primary" @click="submitForm(1)">
              发布到众茶通App
            </el-button>
            <el-button v-if="postForm.type === 0 || postForm.type === 2" type="success" @click="submitForm(2)">
              发布到众茶通小程序
            </el-button>
          </div>
        </el-form-item>

      </div>
    </el-form>

    <div v-if="activeStep == 2" style="padding: 50px;">
      <el-card class="box-card" shadow="hover">
        <div slot="header" class="clearfix">
          <span>分润列表</span>
          <el-button v-if="showSupplyBtn" style="float: right;" type="success" size="mini" @click="addRateSupplier(1)">添加供货供应商</el-button>
          <el-button style="float: right; margin-right: 5px;" type="primary" size="mini" @click="addRateSupplier(2)">添加分润供应商</el-button>
        </div>
        <el-table :data="goodRateData" fit highlight-current-row row-key="id" style="width: 100%;">
          <el-table-column label="供应商名称" prop="companyName" align="center" />
          <el-table-column label="手机号" prop="username" align="center" />
          <el-table-column label="分润比例" prop="splitRate" align="center" />
          <el-table-column label="类型" align="center">
            <template slot-scope="{row}">
              <el-tag v-if="row.splitType == 1" type="success">供货供应商</el-tag>
              <div v-if="row.splitType == 2">
                <el-tag v-if="row.isCounter == 1" type="primary">专柜供应商</el-tag>
                <el-tag v-else-if="row.isCounter == 0 && !row.isGy" type="primary">分润供应商</el-tag>
                <el-tag v-else-if="row.isCounter == 0 && row.isGy" type="primary">产品供应商</el-tag>
              </div>
              <el-tag v-if="row.splitType == 3" type="warning">当前商家</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="300px" class-name="small-padding fixed-width" fixed="right">
            <template slot-scope="{row}">
              <el-button v-if="row.splitType ==2 && row.isCounter == 0 && productType == 12" type="success" size="mini" @click="handleGy(row)">
                标记产品供应商
              </el-button>
              <el-button v-if="row.splitType ==2 && row.isCounter == 0 && productType == 12" type="primary" size="mini" @click="handleChildDialog(row)">
                子分润列表
              </el-button>
              <el-button v-if="row.splitType != 3" type="danger" size="mini" @click="handleDeleteRate(row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
      <el-button type="success" @click="finishSetRate()">完成</el-button>

      <el-dialog title="供应商列表" :visible.sync="dialogFormVisible" width="900px">
        <div class="filter-container">
          <el-input v-model="filterListQuery.companyName$lk" placeholder="商户名称" class="filter-item" clearable />
          <el-input v-model="filterListQuery.username" placeholder="注册电话" class="filter-item" clearable />
          <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="getFilterList">
              查询
          </el-button>
        </div>

        <el-table :data="filterData" border fit highlight-current-row row-key="id" style="width: 100%;">
          <el-table-column label="供应商名称" prop="companyName" align="center" />
          <el-table-column label="手机号" prop="username" align="center" />
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right">
            <template slot-scope="{row}">
              <el-button type="success" size="mini" @click="handleSelect(row)">
                入选
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <Pagination :total="filterTotal" :page.sync="filterListQuery.pageNo" :limit.sync="filterListQuery.pageSize"
        @pagination="getFilterList" />
      </el-dialog>

      <el-dialog title="编辑分润比例" :visible.sync="dialogSplitRateFormVisible" append-to-body>
        <el-input v-model="selectSplitRate" placeholder="请输入"/>
        <div v-if="productType == 10">
          <el-radio v-model="isCounter" label="0">分润供应商</el-radio>
          <el-radio v-model="isCounter" label="1">专柜供应商</el-radio>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogSplitRateFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleEditSplitRate">确 定</el-button>
        </div>
      </el-dialog>

      <el-dialog title="子分润列表" :visible.sync="childRateDialogVisible" width="900px">
        <div class="filter-container">
          <div>父比例：{{ selectParentRate.splitRate }}</div>
          <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="getChildList">
              查询
          </el-button>
          <el-button v-waves class="filter-item" type="success" icon="el-icon-search" @click="addChild">
              添加
          </el-button>
        </div>

        <el-table :data="childData" border fit highlight-current-row row-key="id" style="width: 100%;">
          <el-table-column label="名称" prop="name" align="center" />
          <el-table-column label="子分润" prop="splitRate" align="center" />
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right">
            <template slot-scope="{row}">
              <el-button type="danger" size="mini" @click="deleteChildRate(row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- <Pagination :total="childTotal" :page.sync="childListQuery.pageNo" :limit.sync="filterListQuery.pageSize"
        @pagination="getFilterList" /> -->
      </el-dialog>

      <el-dialog title="编辑子分润比例" :visible.sync="dialogChildRateFormVisible" append-to-body>
        <el-form ref="editChildRateForm" :rules="editChildRateFormRules" :model="editChildRateForm" label-position="right" label-width="110px">
          <el-form-item label="名称" prop="name">
            <el-input v-model.trim="editChildRateForm.name" />
          </el-form-item>
          <el-form-item label="分润比例" prop="splitRate">
            <el-input v-model.trim="editChildRateForm.splitRate" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogChildRateFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="saveChildRate">确 定</el-button>
        </div>
      </el-dialog>

    </div>
  </div>
</template>

<script>
import {mapGetters} from 'vuex'
import waves from '@/directive/waves' // waves directive
import Pagination from '@/components/Pagination'
import Tinymce from '@/components/Tinymce'
import UploadImage from '@/components/UploadImage'
import DatePicker from '@/components/DatePicker'
import Upload from '@/components/Upload'
import UpImgs from '@/components/Upload/UpImgs'
import MDinput from '@/components/MDinput'
import Cascader from '@/components/Cascader'
import AddressCascader from '@/components/AddressCascader'
import { categoryPageVoByQo, productSave, secKillProductSave, agentProductSave, activityProductSave, 
  productGetById, productSplitSave, productSplitUpdate, productSplitPageByQo, productSplitRemoveByIds, getProxyBrandList,
  splitRecordPage, saveSplitRecord, updateSplitRecord, removeSplitRecord } from '@/api/product'
import { storePageByQo } from '@/api/store'
import { attributePageByQo } from '@/api/attribute'
import { SupplierQueryList } from '@/api/supplier'

const defaultForm = {
  id: 0,
  name: '',
  sequence: '',
  isSample: false,
  isStock: false,
  isFinanceProduct: false,
  categoryId: '',
  categoryIds:'',
  identifier: '',
  status: 1,
  priceType: 1,
  price: '',
  priceText: '',
  unit: '',
  startProvinceId: '',
  startProvinceName: '',
  startCityId: '',
  startCityName: '',
  startDistrictId: '',
  startDistrictName: '',
  saleNum: '',
  starNum: '',
  remark: '',
  image: '',
  images: '',
  productVideo: '',
  skuList: '',
  type: 0,
  splitType: 1,
}
const skuItemDefault = {
  id: 0,
  name: '',
  identifier: '',
  priceType: 1,
  price: '',
  unit: '',
  store: '',
  saleNum: '',
  startNum: '',
}

export default {
  name: 'ProductSave',
  directives: { waves },
  props: {
    paramId: {
      default: 0,
      type: Number,
    },
    paramProductType: {
      default: '0',
      type: String,
    },
    paramIsCopySecKillGood: {
      default: '',
      type: String
    },
    paramIsCopyActivityGood: {
      default: '',
      type: String
    },
    paramIsCopyZCTGood: {
      default: '',
      type: String
    },
    paramIsActivityGood: {
      default: '',
      type: String
    },
    paramIsCopyZcyxSecKillGood: {
      default: '',
      type: String
    },
    paramIsCopyZcyxBarGood: {
      default: '',
      type: String
    },
    paramIsCopyZcyxAgentGood: {
      default: '',
      type: String
    },
  },
  components: { Tinymce, MDinput, Upload, UpImgs, Cascader, AddressCascader, UploadImage, DatePicker, Pagination},
  data() {
    const validateDate = (rule, value, callback) => {
      if (!this.postForm.seckillBeginTime || !this.postForm.seckillEndTime) {
        callback(new Error('请选择时间'))
      } else if (new Date(this.postForm.seckillBeginTime).getTime() < new Date().getTime()) {
        callback(new Error('起始时间必须晚于当前时间'))
      } else if(this.postForm.startDate == new Date().getTime()) {
				callback(new Error('起始时间不能等于当前时间'))
			} else {
        callback()
      }
    }

    const validateCity = (rule, value, callback) => {
      if (!this.postForm.startDistrictId) {
        callback(new Error('请选择省市区'))
      } else {
        callback()
      }
    }
    return {
      postForm: Object.assign({}, defaultForm),
      categoryData: [],
      zcyxCategoryData: [],
      categoryId: '',
      categoryIds: '',
      zcyxCategoryId: '',
      zcyxCategoryIds: '',
      storeData: [],
      storeId: '',
      storeIds: '',
      props: { value: 'id', label: 'name' },
      selectedOptions: [],
      loading: false,
      rules: {
        image: [{ required: true, message: '请选择', trigger: 'blur' }],
        categoryId: [{ required: true, message: '请选择', trigger: 'blur' }],
        zcyxCategoryId: [{ required: true, message: '请选择', trigger: 'blur' }],
        storeId: [{ required: true, message: '请选择', trigger: 'blur' }],
        price: [{required: true,message: '请选择' , trigger: 'blur'}],
        unit: [{ required: true, message: '请输入', trigger: 'blur' }],
        name: [{ required: true, message: '请输入', trigger: 'blur' }],
        remark: [{ required: true, message: '请输入图文详情', trigger: 'blur' }],
        proxyBrandId: [{ required: true, message: '请输入图文详情', trigger: 'blur' }],
        city: [{ required: true, trigger: 'blur', validator: validateCity }],
        startDate: [{validator: validateDate}],
        splitType: [{ required: true, message: '请选择', trigger: 'blur' }],
      },
      statusJson: [
        { value: 0, label: '下架' },
        { value: 1, label: '上架' }
      ],
      images: [],
      productId: 0,
      skuList: [],
      attributeList: [],
      goodsClassification:'',
      goodsYear:'',
      productionPlaceOptions: [],
      warehouseOptions: [],
      requiredWarehouse: false,
      requiredProductionPlace: false,
      productType: 0,
      // 0:普通商品，
      // 1:秒杀商品，
      // 2:经销商品 
      // 3:活动专区商品 
      // 4:微商城商品 
      // 5:众茶优选普通商品 
      // 6：众茶优选秒杀商品 
      // 7:众茶优选推广秒杀商品 
      // 8:众茶优选积分商品 
      // 9:众茶优选经销商品 
      priceLabel: "",
      guestPriceLabel: "",
      title: "",
      activeStep: 1,
      goodRateData: [],
      dialogFormVisible: false,
      filterListQuery: {
        companyName$lk: "",
        username: "",
        status: 1,
        pageNo: 1,
        pageSize: 10
      },
      filterData: [],
      filterTotal: 0,
      childRateDialogVisible: false,
      childListQuery: {
        originalSplitId: '',
        pageNo: 1,
        pageSize: 999
      },
      childData: [],
      childTotal: 0,
      selectParentRate: {},
      dialogChildRateFormVisible: false,
      editChildRateFormRules: {
        name: [{ required: true, message: '请填写', trigger: 'change' }],
        splitRate: [{ required: true, message: '请填写', trigger: 'change' }],
      },
      editChildRateForm: {
        name: '',
        originalSplitId: '',
        originalSplitRate: '',
        productId: '',
        splitRate: '',
      },
      commonOption: [
        { value: 1, label: '是' },
        { value: 0, label: '否' }
      ],
      highPriceLabel: '',
      brandOption: [],
      brandQuery: {
        pageNo: 1,
        pageSize: 999,
      },
      dialogSplitRateFormVisible: false,
      selectSplitRate: '',
      isCounter: '0',
      selectSupplier: {},
      selectType: 1,// 1: 添加供货供应商 2：添加分润供应商
      splitTypeOption: [
        { value: 1, label: '无' },
        { value: 2, label: 'a1类' },
        { value: 3, label: 'a2类' },
        { value: 4, label: 'b1类' },
        { value: 5, label: 'b2类' },
        { value: 6, label: 'c类' },
      ],
      showSupplyBtn: 1,
      showStock: 0
    }
  },
  computed: {
    ...mapGetters(['userInfo']),
  },
  inject: ['reload'],//引入
  watch: {
    images(val) {
      if (val && val.length) {
        this.postForm.images = val.map(item => {
          return item
        }).join(',');
      } else {
        this.postForm.images = '';
      }
    },
    categoryId(val) {
      this.resetForm()
      this.$set(this.postForm, `categoryId`, this.$refs['categoryId'].getIds(val))
      
      this.getAttributeData()
    },
    zcyxCategoryId(val) {
      this.$set(this.postForm, `zcyxCategoryId`, this.$refs['zcyxCategoryId'].getIds(val))
    },
    storeId(val) {
      this.$set(this.postForm, `storeId`, this.$refs['storeId'].getIds(val))
    },
    $route: {
      handler: function(route) {
        let id = Number(this.$route.query.id);
        setTimeout(() => {
          if (!isNaN(id)) {
            if (id && this.productId) {
              if (id != this.productId) {
                this.reload();//刷新
              }
            } else if (id == 0 || this.productId == 0) {
              if (id != this.productId) {
                this.reload();//刷新
              }
            }
          }
        }, 500);
      },
      immediate: true
    }
  },
  created() {
    this.productId = this.paramId
    this.productType = Number(this.paramProductType)
    
    let tempName = ''
    if (this.userInfo.id == '48244') {
      tempName = '众茶会'
      this.showStock = 1
    } else {
      tempName = '众茶优选'
      this.showStock = 0
    }

    if (this.productType == 0) {// 0:普通商品，
      this.guestPriceLabel = "零售价"
      this.priceLabel = "会员价（元）"
      this.title = "商品管理"
    } else if (this.productType == 1) {// 1:秒杀商品，
      this.priceLabel = "秒杀价（元）"
      this.title = "秒杀商品管理"
    } else if (this.productType == 2) {// 2:经销商品 
      this.priceLabel = "经销价（元）"
      this.title = "经销商品管理"
    } else if (this.productType == 3) {// 3:活动专区商品 
      this.guestPriceLabel = "零售价"
      this.priceLabel = "活动专区（元）"
      this.title = "活动商品管理"
    } else if (this.productType == 4) {// 4:微商城商品 
      this.priceLabel = "会员价（元）"
      this.title = "微商城商品管理"
    } else if (this.productType == 5) {// 5:众茶优选普通商品 
      this.guestPriceLabel = "建议零售价"
      this.priceLabel = "会员价"
      this.highPriceLabel = '高级会员价'
      this.title = tempName + "普通商品管理"
    } else if (this.productType == 6) {// 6：众茶优选秒杀商品 
      this.guestPriceLabel = "建议零售价"
      this.priceLabel = "秒杀价"
      this.title = tempName + "秒杀商品管理"
    } else if (this.productType == 7) {// 7:众茶优选推广秒杀商品 
      this.guestPriceLabel = "建议零售价"
      this.priceLabel = "秒杀价"
      this.title = tempName + "推广秒杀商品管理"
    } else if (this.productType == 8) {// 8:众茶优选积分商品 
      this.priceLabel = "价格"
      this.title = tempName + "积分商品管理"
    } else if (this.productType == 9) {// 9:众茶优选经销商品 
      this.guestPriceLabel = "建议零售价"
      this.priceLabel = "分销商价格"
      this.highPriceLabel = '代理商价格'
      this.title = tempName + "经销商品管理"
    } else if (this.productType == 10) {// 10:众茶优选专柜商品 
      this.guestPriceLabel = "建议零售价"
      this.priceLabel = "会员价"
      this.highPriceLabel = '高级会员价'
      this.title = tempName + "专柜商品管理"
    } else if (this.productType == 11) {// 11:众茶优品商品 
      this.guestPriceLabel = ""
      this.priceLabel = "会员价"
      this.title = "众茶优品商品管理"
    } else if (this.productType == 12) {// 12:服务商专区商品 
      this.guestPriceLabel = ""
      this.priceLabel = "会员价"
      this.title = "服务商专区商品管理"
    } else {
      this.guestPriceLabel = ""
      this.priceLabel = "会员价"
      this.title = "商城商品管理"
    }

    if (this.productType == 5 || this.productType == 6  || this.productType == 7 || 
    this.productType == 8 || this.productType == 9 || this.productType == 10) {//众茶优选商品
      this.getZCYXCategory()
    }

    if (this.productType == 9) {// 获取经销商品品牌
      this.getBrandData()
    }
    
    this.getStoreData()
    this.getCategory()
  },
  methods: {
    init(val) {
      this.getAttributeData()
      this.$nextTick(() => {
        if (val.startDistrictId) {
          this.selectedOptions = [val.startProvinceId.toString(), val.startCityId.toString(), val.startDistrictId.toString()]
        } else {
          this.selectedOptions = ''
        }
        if (val.productionDistrictId) {
          this.productionPlaceOptions = [val.productionProvinceId.toString(), val.productionCityId.toString(), val.productionDistrictId.toString()]
        } else {
          this.productionPlaceOptions = ''
        }
        if (val.warehouseDistrictId) {
          this.warehouseOptions = [val.warehouseProvinceId.toString(), val.warehouseCityId.toString(), val.warehouseDistrictId.toString()]
        } else {
          this.warehouseOptions = ''
        }
        
        if (val.images) {
          val.images.split(',').forEach(item => {
            this.images.push(item)
          });
        }
        this.categoryIds = val.categoryId ? val.categoryId.toString() : ''
        this.zcyxCategoryIds = val.zcyxCategoryId ? val.zcyxCategoryId.toString() : ''
        this.storeIds = val.storeId ? val.storeId.toString() : ''
        this.skuList = val.skuList || []
      })
    },
    selectAddressDetail(value) {
      if (value) {
        this.$set(this.postForm, `startProvinceId`, value.provinceId)
        this.$set(this.postForm, `startProvinceName`, value.provinceName)
        this.$set(this.postForm, `startCityId`, value.cityId)
        this.$set(this.postForm, `startCityName`, value.cityName)
        this.$set(this.postForm, `startDistrictId`, value.districtId)
        this.$set(this.postForm, `startDistrictName`, value.districtName)
      } else {
        this.$set(this.postForm, `startProvinceId`, '')
        this.$set(this.postForm, `startProvinceName`, '')
        this.$set(this.postForm, `startCityId`, '')
        this.$set(this.postForm, `startCityName`, '')
        this.$set(this.postForm, `startDistrictId`, '')
        this.$set(this.postForm, `startDistrictName`, '')
      }
    },
    getBrandData() {
      getProxyBrandList(this.brandQuery).then((response) => {
        this.brandOption = response.list.map((item) => {
          return { value: item.id, label: item.name }
        })
      });
    },
    getCategory() {
      categoryPageVoByQo().then((res) => {
        this.$set(this, 'categoryData', res || [])
        if (this.productId) {
          this.fetchData(this.productId)
        }
      })
    },
    getZCYXCategory() {
      categoryPageVoByQo( {companyType: 0} ).then((res) => {
        this.$set(this, 'zcyxCategoryData', res || [])
      })
    },
    getStoreData() {
      storePageByQo().then((res) => {
        const list = res || []
        this.storeData = list.filter(item => {
          return item.children && item.children.length
        })
      })
    },
    fetchData(id) {
      productGetById({ id: id }).then(response => {
        this.postForm = response
        if (this.paramIsCopyZCTGood == '1') {// 众茶通App商品复制到众茶通
          this.postForm.type = 2
        }
        if (this.postForm.remark) {
          this.$refs.editor.setContent(this.postForm.remark)
        }
        this.init(response);
      }).catch(err => {
        console.log(err)
      })
    },
    validateSKU() {
      let success = true;
      if (this.skuList && this.skuList.length > 0) {
        this.skuList.forEach(item => {
          if (!item.name || (!item.price && item.price !== 0) || (!item.store && item.store !== 0) || (!item.weight && item.weight !== 0) || (!item.store && item.store !== 0) || (!item.startNum)) { 
            success = false
          }
        })
        if (!success) {
          this.$message.error('商品规格中有必填字段未填写')
        }
        return success
      } else {
        this.$message.error('请添加商品规格')
        success = false
        return success
      }
    },
    submitForm(type) {
      this.$refs['postForm'].validate((valid) => {
        if (valid) {
          if (!this.validateSKU()) {
            return
          }
          this.postForm.type = type
          this.postForm.skuList = this.skuList
          this.postForm.isNullUpdate = 1
          // this.postForm.skuList = JSON.stringify(this.skuList)
          this.loading = true
          delete this.postForm.createTime

          let isEdit = false

          if (this.paramIsCopySecKillGood == '1') {//众茶通商品复制到秒杀商品
            delete this.postForm.id
            isEdit = false
          } else if (this.paramIsCopyActivityGood == '1') {//众茶通商品复制到活动专区
            delete this.postForm.id
            isEdit = false
          } else if (this.paramIsCopyZCTGood == '1') {//众茶通App商品复制到众茶通
            delete this.postForm.id
            isEdit = false
          } else if (this.paramIsCopyZcyxSecKillGood == '1') {//众茶优选普通商品复制到众茶优选秒杀商品
            delete this.postForm.id
            isEdit = false
          } else if (this.paramIsCopyZcyxBarGood == '1') {//众茶优选普通商品复制到众茶优选专柜商品
            isEdit = true
          } else if (this.paramIsCopyZcyxAgentGood == '1') {//众茶优选普通商品复制到众茶优选经销商品
            delete this.postForm.id
            isEdit = false
          } else {
            isEdit = this.productId > 0;
          }

          if (this.productType == 1) {// 小程序秒杀商品
            secKillProductSave(this.postForm, isEdit).then(() => {
              this.loading = false

              this.$message({
                message: `商品${isEdit ? '编辑' : '添加'}成功`,
                type: 'success'
              });

              // 调用全局挂载的方法,关闭当前标签页
              this.$store.dispatch("tagsView/delView", this.$route);
              
              this.$router.push({
                path: "/shop/secProductList",
                query: {
                  t: Date.now()
                }
              });
            }).catch(() => {
              this.loading = false
            })
          } else if (this.productType == 2) {// 经销商品
            agentProductSave(this.postForm, isEdit).then(() => {
              this.loading = false

              this.$message({
                message: `商品${isEdit ? '编辑' : '添加'}成功`,
                type: 'success'
              });
              
              // 调用全局挂载的方法,关闭当前标签页
              this.$store.dispatch("tagsView/delView", this.$route);

              this.$router.push({
                path: "/customer/agentProductList",
                query: {
                  t: Date.now()
                }
              });
            }).catch(() => {
              this.loading = false
            })
          } else if (this.productType == 3) {// 活动专区商品
            activityProductSave(this.postForm, isEdit).then(() => {
              this.loading = false

              this.$message({
                message: `商品${isEdit ? '编辑' : '添加'}成功`,
                type: 'success'
              });
              
              // 调用全局挂载的方法,关闭当前标签页
              this.$store.dispatch("tagsView/delView", this.$route);
              
              this.$router.push({
                path: "/shop/activityProductList",
                query: {
                  t: Date.now()
                }
              });
            }).catch(() => {
              this.loading = false
            })
          } else if (this.productType == 4) {// 微商城商品
            productSave(this.postForm, isEdit).then(() => {
              this.loading = false

              this.$message({
                message: `商品${isEdit ? '添加' : '编辑'}成功`,
                type: 'success'
              });
              
              // 调用全局挂载的方法,关闭当前标签页
              this.$store.dispatch("tagsView/delView", this.$route);

              this.$router.push({
                path: "/microShop/microShopProductList",
                query: {
                  t: Date.now()
                }
              });
            }).catch(() => {
              this.loading = false
            })
          } else if (this.productType == 5) {// 众茶优选普通商品
            if (this.postForm.isNewProduct === "") {
              this.postForm.isNewProduct = 0
            }
            if (this.postForm.isTailCargo === "") {
              this.postForm.isTailCargo = 0
            }
            if (this.postForm.isHotProduct === "") {
              this.postForm.isHotProduct = 0
            }
            productSave(this.postForm, isEdit).then((res) => {
              this.loading = false

              this.$message({
                message: `商品${isEdit ? '添加' : '编辑'}成功`,
                type: 'success'
              });

              this.productId = res
              this.activeStep = 2
              this.getProductSplitRateData()
              
              // 调用全局挂载的方法,关闭当前标签页
              // this.$store.dispatch("tagsView/delView", this.$route);

              // this.$router.push({
              //   path: "/zcyx/zcyxProductList",
              //   query: {
              //     t: Date.now()
              //   }
              // });
            }).catch(() => {
              this.loading = false
            })
          } else if (this.productType == 6) {// 众茶优选秒杀商品
            if (this.paramIsCopyZcyxSecKillGood == '1') {
              if (this.postForm.skuList && this.postForm.skuList.length > 0) {
                this.postForm.skuList[0].seniorMemberPrice = ''
              }
            }
            secKillProductSave(this.postForm, isEdit).then((res) => {
              this.loading = false

              this.$message({
                message: `商品${isEdit ? '编辑' : '添加'}成功`,
                type: 'success'
              });

              this.productId = res
              this.activeStep = 2
              this.getProductSplitRateData()

              // 调用全局挂载的方法,关闭当前标签页
              // this.$store.dispatch("tagsView/delView", this.$route);
              
              // this.$router.push({
              //   path: "/zcyx/zcyxProductSeckillList",
              //   query: {
              //     t: Date.now()
              //   }
              // });
            }).catch(() => {
              this.loading = false
            })
          } else if (this.productType == 7) {// 众茶优选推广秒杀商品
            let param = Object.assign({}, this.postForm)
            param.isExtension = '1'
            secKillProductSave(param, isEdit).then((res) => {
              this.loading = false

              this.$message({
                message: `商品${isEdit ? '编辑' : '添加'}成功`,
                type: 'success'
              });

              this.productId = res
              this.activeStep = 2
              this.getProductSplitRateData()

              // 调用全局挂载的方法,关闭当前标签页
              // this.$store.dispatch("tagsView/delView", this.$route);
              
              // this.$router.push({
              //   path: "/zcyx/zcyxProductSeckillPopularizeList",
              //   query: {
              //     t: Date.now()
              //   }
              // });
            }).catch(() => {
              this.loading = false
            })
          } else if (this.productType == 8) {// 众茶优选积分商品
            let param = Object.assign({}, this.postForm)
            productSave(param).then((res) => {
              this.loading = false

              this.$message({
                message: `商品${isEdit ? '编辑' : '添加'}成功`,
                type: 'success'
              });

              // 调用全局挂载的方法,关闭当前标签页
              this.$store.dispatch("tagsView/delView", this.$route);

              this.$router.push({
                path: "/zcyx/zcyxProductScoreList",
                query: {
                  t: Date.now()
                }
              });
            }).catch(() => {
              this.loading = false
            })
          } else if (this.productType == 9) {// 众茶优选经销商品
            agentProductSave(this.postForm, isEdit).then((res) => {
              this.loading = false

              this.$message({
                message: `商品${isEdit ? '编辑' : '添加'}成功`,
                type: 'success'
              });

              this.productId = res
              this.activeStep = 2
              this.getProductSplitRateData()
            }).catch((err) => {
              console.log(err)
              this.loading = false
            })
          } else if (this.productType == 10) {// 众茶优选专柜商品
            let param = Object.assign({}, this.postForm)
            param.isSeckill = 4
            productSave(param).then((res) => {
              this.loading = false

              this.$message({
                message: `商品${isEdit ? '编辑' : '添加'}成功`,
                type: 'success'
              });

              this.productId = res
              this.activeStep = 2
              this.getProductSplitRateData()
            }).catch(() => {
              this.loading = false
            })
          } else if (this.productType == 11) {// 众茶优品商品
            let param = Object.assign({}, this.postForm)
            param.isSeckill = 0
            productSave(param).then((res) => {
              this.loading = false

              this.$message({
                message: `商品${isEdit ? '编辑' : '添加'}成功`,
                type: 'success'
              });

              this.$store.dispatch("tagsView/delView", this.$route);

              this.$router.push({
                path: "/shop/bestProductList",
                query: {
                  t: Date.now()
                }
              });
            }).catch(() => {
              this.loading = false
            })
          } else if (this.productType == 12) {// 服务商专区商品
            let param = Object.assign({}, this.postForm)
            param.isServeProduct = 1
            productSave(param).then((res) => {
              this.loading = false

              this.$message({
                message: `商品${isEdit ? '编辑' : '添加'}成功`,
                type: 'success'
              });

              this.productId = res
              this.activeStep = 2
              this.showSupplyBtn = 0
              this.getProductSplitRateData()
            }).catch(() => {
              this.loading = false
            })
          } else {// 普通商品
            productSave(this.postForm, isEdit).then(() => {
              this.loading = false

              this.$message({
                message: `商品${isEdit ? '添加' : '编辑'}成功`,
                type: 'success'
              });
              
              // 调用全局挂载的方法,关闭当前标签页
              this.$store.dispatch("tagsView/delView", this.$route);

              this.$router.push({
                path: "/shop/productList",
                query: {
                  t: Date.now()
                }
              });
            }).catch(() => {
              this.loading = false
            })
          }
        }
      })
    },
    addSkuItem() {
      if (!this.skuList || this.skuList.length < 1) {
        this.skuList = [];
      }
      if (this.productType == 1 || this.productType == 6 || this.productType == 7 || this.productType == 11) {
        if (this.skuList && this.skuList.length > 0) {
          this.$message.error("只能添加一个商品规格")
          return
        }
      }
      
      //未知原因直接传值会出现复制输入的值和修改同步修改的问题
      const item = Object.assign({}, skuItemDefault)
      this.skuList.push(item);
    },
    deleteSkuItem(index) {
      this.skuList.splice(index, 1);
    },
    getAttributeData() {
      if (this.postForm.categoryId) {
        attributePageByQo({categoryId: this.postForm.categoryId}).then(response => { 
          this.attributeList = response
          this.updateForm()
        }).catch(error => {
          console.log(error);
        })
      } else {
        this.attributeList = []
      }
    },
    updateForm() {
      this.requiredWarehouse = false
      this.requiredProductionPlace = false

      let productionPlaceIndex = this.attributeList.findIndex((value, index, arr) => {
        return value.fieldName === 'productionPlace'
      })
      if (productionPlaceIndex >= 0) {
        this.attributeList.splice(productionPlaceIndex,1)
        this.requiredProductionPlace = true
      }

      let warehouseIndex = this.attributeList.findIndex((value, index, arr) => {
        return value.fieldName === 'warehouse'
      })
      if (warehouseIndex >= 0) {
        this.attributeList.splice(warehouseIndex,1)
        this.requiredWarehouse = true
      }
      
      for (let index = 0; index < this.attributeList.length; index++) {
        let item = this.attributeList[index];
        if (item.required == 1) {
          var newRules = [{ required: true, message: '请输入', trigger: 'change' }]
          this.$set(this.rules, item.fieldName, newRules)
        }
        
        if (item.fieldName === 'productionDate') {
          this.handleInput('', item)
        }
        if (item.fieldName === 'classification') {
          this.handleInput('', item)
        }
      }

      this.$nextTick(() => {
        this.$refs['postForm'].clearValidate()
        this.$forceUpdate()
      })
    },
    resetForm() {
      if (this.requiredProductionPlace) {
        this.productionPlaceOptions = ''
        delete this.postForm.productionProvinceId
        delete this.postForm.productionProvinceName
        delete this.postForm.productionCityId
        delete this.postForm.productionCityName
        delete this.postForm.productionDistrictId
        delete this.postForm.productionDistrictName
        delete this.postForm.productionAddress

        this.requiredProductionPlace = false
      }
      if (this.requiredWarehouse) {
        this.warehouseOptions = ''
        delete this.postForm.warehouseProvinceId
        delete this.postForm.warehouseProvinceName
        delete this.postForm.warehouseCityId
        delete this.postForm.warehouseCityName
        delete this.postForm.warehouseDistrictId
        delete this.postForm.warehouseDistrictName

        this.requiredWarehouse = false
      }
      
      for (let item of this.attributeList) {
        if (this.postForm.hasOwnProperty(item.fieldName)) {
          delete this.postForm[item.fieldName]
        }
      }

      this.goodsYear = ''
      this.goodsClassification = ''
      this.postForm.name = ''
    },
    handleInput(val, attribute) {
      if (attribute.fieldName === 'brand' || attribute.fieldName === 'description' || attribute.fieldName === 'productionDate' || attribute.fieldName === 'classification' 
      || attribute.fieldName === 'packagingForm' || attribute.fieldName === 'capacity') {
        if (attribute.fieldName === 'productionDate') {
           this.goodsYear = ''
          if (this.postForm.productionDate && this.postForm.productionDate.indexOf('-') != -1) {
            this.goodsYear = this.postForm.productionDate.split("-")[0] + '年'
          }
        }   
        
        if (attribute.fieldName === 'classification') {
          this.goodsClassification= ''
          for (const iterator of attribute.dinnerAttributeDetailList) {
            if (this.postForm.classification && iterator.id.toString() === this.postForm.classification.toString()) {
              this.goodsClassification = iterator.name
            }
          }
        }

        let categoryName = ''

        let tempCategoryId = ''
        if (this.categoryId && this.categoryId.length == 2) {
          tempCategoryId = this.categoryId[1] // 本地修改后的最新属性
        } else {
          tempCategoryId = this.categoryIds // 请求后的最新属性
        }
        if (this.categoryData && this.categoryData.length > 0
        && tempCategoryId) {
          this.categoryData.forEach(element => {
            element.children.forEach(item => {
              if (item.id == tempCategoryId) {
                categoryName = item.name
              }
            });
          });
        }

        let brand = this.postForm.brand ? this.postForm.brand : ''
        let description = this.postForm.description ? this.postForm.description : ''
        let packagingForm = this.postForm.packagingForm ? this.postForm.packagingForm : ''
        let capacity = this.postForm.capacity ? this.postForm.capacity : ''
        this.postForm.name = brand + this.goodsYear + description + categoryName + packagingForm + capacity
      }
    },
    handleAddress(value, type) {
      if (type === 'productionPlace') {
        if (value) {
          this.$set(this.postForm, `productionProvinceId`, value.provinceId)
          this.$set(this.postForm, `productionProvinceName`, value.provinceName)
          this.$set(this.postForm, `productionCityId`, value.cityId)
          this.$set(this.postForm, `productionCityName`, value.cityName)
          this.$set(this.postForm, `productionDistrictId`, value.districtId)
          this.$set(this.postForm, `productionDistrictName`, value.districtName)
        } else {
          this.$set(this.postForm, `productionProvinceId`, '')
          this.$set(this.postForm, `productionProvinceName`, '')
          this.$set(this.postForm, `productionCityId`, '')
          this.$set(this.postForm, `productionCityName`, '')
          this.$set(this.postForm, `productionDistrictId`, '')
          this.$set(this.postForm, `productionDistrictName`, '')
        }
      }
      if (type === 'warehouse') {
        if (value) {
          this.$set(this.postForm, `warehouseProvinceId`, value.provinceId)
          this.$set(this.postForm, `warehouseProvinceName`, value.provinceName)
          this.$set(this.postForm, `warehouseCityId`, value.cityId)
          this.$set(this.postForm, `warehouseCityName`, value.cityName)
          this.$set(this.postForm, `warehouseDistrictId`, value.districtId)
          this.$set(this.postForm, `warehouseDistrictName`, value.districtName)
        } else {
          this.$set(this.postForm, `warehouseProvinceId`, '')
          this.$set(this.postForm, `warehouseProvinceName`, '')
          this.$set(this.postForm, `warehouseCityId`, '')
          this.$set(this.postForm, `warehouseCityName`, '')
          this.$set(this.postForm, `warehouseDistrictId`, '')
          this.$set(this.postForm, `warehouseDistrictName`, '')
        }
      }
    },
    addRateSupplier(type) {
      this.selectType = type
      this.dialogFormVisible = true
    },
    getFilterList() {
      SupplierQueryList(this.filterListQuery).then(response => {
        this.filterData = response.list || []
        this.filterTotal = response.totalCount
      })
    },
    handleGy(row) {
      productSplitUpdate({ 
        id: row.id,
        productId:this.productId, 
        splitMemberId: row.splitMemberId,
        splitRate: row.splitRate, 
        isGy: 1,
        isCounter: 0,
        splitType: 2, 
        type: 1
      }).then(res => {
        this.getProductSplitRateData()
      })
      .catch((err) => {
        console.log(err)
      })
    },
    handleSelect(row) {
      if (this.selectType == 1) { //添加供货供应商
        this.dialogFormVisible = false

        productSplitSave({ 
          productId:this.productId, 
          splitMemberId: row.id, 
          isCounter: this.isCounter,
          splitType: 1, 
          type: 1
        }).then(res => {
          this.getProductSplitRateData()
        })
        .catch((err) => {
          console.log(err)
        })
      } else {// 添加分润供应商
        this.selectSupplier = row
        this.selectSplitRate = ''
        this.dialogSplitRateFormVisible = true
      }
    },
    getProductSplitRateData() {
      productSplitPageByQo({ productId:this.productId, pageNo: 1, pageSize: 99 }).then(res => {
        this.goodRateData = res.list
      })
      .catch((err) => {
        console.log(err)
      })
    },
    handleDeleteRate(row) {
      this.$confirm('是否继续删除？').then(() => {
        productSplitRemoveByIds({ ids: row.id}).then(res => {
          this.$message({
            message: '操作成功！',
            type: 'success'
          });
          
          this.getProductSplitRateData()
        })
        .catch((err) => {
          console.log(err)
        })
      })
    },
    handleEditSplitRate() {
      productSplitSave({ 
        productId:this.productId, 
        splitMemberId: this.selectSupplier.id, 
        splitRate: this.selectSplitRate, 
        isCounter: this.isCounter,
        splitType: 2,
        type: 1
      }).then(res => {
        this.dialogSplitRateFormVisible = false
        this.getProductSplitRateData()
      })
      .catch((err) => {
        console.log(err)
      })
    },
    finishSetRate() {
      if (this.goodRateData.length > 0) {
        this.closeSetView()
      } else {
        this.$message.error("请编辑分润供应商")
      }
    },
    closeSetView() {
      // 调用全局挂载的方法,关闭当前标签页
      this.$store.dispatch("tagsView/delView", this.$route);

      let path = ""
      if (this.productType == 5) {// 众茶优选普通商品
        path = "/zcyx/zcyxProductList"
      } else if(this.productType == 6) {// 众茶优选秒杀商品
        path = "/zcyx/zcyxProductSeckillList"
      } else if(this.productType == 7) {//众茶优选推广秒杀商品
        path = "/zcyx/zcyxProductSeckillPopularizeList"
      } else if(this.productType == 9) {// 众茶优选经销商品
        path = "/zcyx/zcyxAgentProductList"
      } else if(this.productType == 10) {// 众茶优选专柜商品
        path = "/zcyx/zcyxBarProductList"
      } else if(this.productType == 12) {// 服务商专区商品
        path = "/shop/serviceProductList"
      }

      this.$router.push({
        path: path,
        query: {
          t: Date.now()
        }
      });
    },
    handlePriceInput(v, row, param) {
      let newValue = v.toString()
      newValue = v
        .replace(/[^\d.]/g, '')
        .replace(/\.{2,}/g, '.')
        .replace('.', '$#$')
        .replace(/\./g, '')
        .replace('$#$', '.')
        .replace(/^(-)*(\d+)\.(\d\d).*$/, '$1$2.$3')
      if (
        newValue.length > 1 &&
        newValue.indexOf('.') !== 1 &&
        newValue.indexOf('0') === 0
      ) {
        newValue = newValue.toString().substring(1)
      }
      row[param] = newValue
      this.$nextTick(() => {
        this.$forceUpdate()
      })
      return newValue
    },
    handleSplitRateInput(v) {
      let newValue = v.toString()
      newValue = v
        .replace(/[^\d.]/g, '')
        .replace(/\.{2,}/g, '.')
        .replace('.', '$#$')
        .replace(/\./g, '')
        .replace('$#$', '.')
        .replace(/^(-)*(\d+)\.(\d\d).*$/, '$1$2.$3')
      if (
        newValue.length > 1 &&
        newValue.indexOf('.') !== 1 &&
        newValue.indexOf('0') === 0
      ) {
        newValue = newValue.toString().substring(1)
      }
      this.selectSplitRate = newValue
      this.$nextTick(() => {
        this.$forceUpdate()
      })
    },
    handleChildDialog(row) {
      this.selectParentRate = row
      this.childRateDialogVisible = true
      this.getChildList()
    },
    getChildList() {
      this.childListQuery.originalSplitId = this.selectParentRate.id
      splitRecordPage(this.childListQuery).then(response => {
        this.childData = response.list || []
        this.childTotal = response.totalCount
      })
    },
    addChild() {
      this.editChildRateForm = {
        name: '',
        originalSplitId: '',
        originalSplitRate: '',
        productId: '',
        splitRate: '',
      }
      this.dialogChildRateFormVisible = true
    },
    saveChildRate() {
      this.editChildRateForm.originalSplitId = this.selectParentRate.id
      this.editChildRateForm.originalSplitRate = this.selectParentRate.splitRate
      this.editChildRateForm.productId = this.productId
      saveSplitRecord(this.editChildRateForm).then(res => {
        this.dialogChildRateFormVisible = false
        this.getChildList()
      })
      .catch((err) => {
        
      })
    },
    deleteChildRate(row) {
      removeSplitRecord({ids: row.id}).then(res => {
        this.getChildList()
      })
      .catch((err) => {
        
      })
    }
  }
}
</script>

<style lang="scss" scoped>
@import "~@/styles/mixin.scss";

.createPost-container {
  position: relative;

  .createPost-main-container {
    padding: 40px 45px 20px 50px;

    .postInfo-container {
      position: relative;
      @include clearfix;
      margin-bottom: 10px;

      .postInfo-container-item {
        float: left;
        margin-right: 20px;
      }
    }
  }

  .word-counter {
    width: 40px;
    position: absolute;
    right: 10px;
    top: 0px;
  }
}

.article-textarea ::v-deep {
  textarea {
    padding-right: 40px;
    resize: none;
    border: none;
    border-radius: 0px;
    border-bottom: 1px solid #bfcbd9;
  }
}
.box-card {
  margin-bottom: 30px;
  .flexItem {
    display: flex;
    align-items: center;
    .fuhao {
      margin-right: 3px;
      font-size: 16px;
      color: red;
    }
    .el-input {
      width: auto;
      flex: 1;
    }
  }
}

.sku_tip {
  font-size: 13px;
  color: gray;
}
</style>
